package com.zlyx.easy.asyn.utils;

import org.springframework.beans.factory.annotation.Autowired;

import com.zlyx.easy.asyn.model.AsynMessage;
import com.zlyx.easy.asyn.supports.AsynMsgSender;
import com.zlyx.easy.core.annotations.SpringBean;
import com.zlyx.easy.core.loggers.Logger;
import com.zlyx.easy.core.utils.ClassUtils;

/**
 * @Auth 赵光
 * @Describle 默认为JMS方式,配置ActiveMQ后为ActiveMQ方式,可以通过引入不同的类型MQ/Redis(easy-redis)来动MQ类型，全自动化配置
 * @2019年9月7日
 */
@SpringBean(todo = { "异步消息发送工具" })
public class MsgUtils {

	public final static String DEFAULT_CHANNEL = "easy-asyn-channel";

	private static AsynMsgSender asynMsgSender;

	public MsgUtils(@Autowired(required = false) AsynMsgSender asynMsgSender) {
		MsgUtils.asynMsgSender = ClassUtils.getInstance(asynMsgSender, AsynMsgSender.class);
		Logger.info("asynMsgSender = {}", asynMsgSender);
	}

	/**
	 * 发布Topic消息(支持的MQ:ActiveMQ、RibbitMQ和RocketMQ, Redis, NSQ)
	 * 
	 * @param channel
	 * @param msg
	 */
	public static void doTopic(String channel, Object msg) {
		Logger.info("channel = {} 发送了一条Topic消息: msg = {}", channel, msg);
		asynMsgSender.doTopic(DEFAULT_CHANNEL, newMessage(channel, msg));
	}

	/**
	 * 发布Queue消息(支持的MQ:ActiveMQ和RocketMQ)
	 * 
	 * @param channel
	 * @param msg
	 */
	public static void doQuque(String channel, Object msg) {
		Logger.info("channel = {} 发送了一条Quque消息: msg = {}", channel, msg);
		asynMsgSender.doQuque(DEFAULT_CHANNEL, newMessage(channel, msg));
	}

	/**
	 * 构建异步消息
	 * 
	 * @param channel
	 * @param msg
	 */
	public static String newMessage(String channel, Object msg) {
		return new AsynMessage(channel, msg).toString();
	}
}
